package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.*;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.*;
import com.zzyl.properties.SecurityProperties;
import com.zzyl.service.UserService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户表服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    DeptMapper deptMapper;
    @Autowired
    PostMapper postMapper;
    @Autowired
    SecurityProperties securityProperties;
    @Autowired
    RoleResourceMapper roleResourceMapper;

    @Override
    public PageBean<UserVo> query(UserDto dto, int pageNum, int pageSize) {
        if (ObjectUtil.isNotEmpty(dto.getDeptNo())) {
            dto.setDeptNo(NoProcessing.processString(dto.getDeptNo()));
        }
        PageHelper.startPage(pageNum, pageSize);
        Page<User> users = userMapper.selectPage(dto);
        PageBean<UserVo> pageBean = PageBean.of(users, UserVo.class);
        if (CollUtil.isEmpty(pageBean.getRecords())) {
            return pageBean;
        }
        pageBean.getRecords().forEach(userVo -> {
            List<Role> roleList = roleMapper.findRoleListByUserId(userVo.getId());

            List<String> id = CollUtil.getFieldValues(roleList, "id", String.class);

            List<String> roleName = CollUtil.getFieldValues(roleList, "roleName", String.class);

            userVo.setRoleVoIds(Set.copyOf(id));

            userVo.setRoleLabels(Set.copyOf(roleName));
        });
        return pageBean;
    }

    @Override
    public void add(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        user.setPassword("123456");
        user.setPassword(DigestUtil.bcrypt(user.getPassword()));
        user.setDataState("0");
        user.setUsername("老龙");
        userMapper.insert(user);
    }

    @Override
    public void delete(Long userIds) {

        userMapper.deleteByPrimaryKey(userIds);
    }

    @Override
    public void update(UserDto userDto) {
        int count = deptMapper.isLowestDept(userDto.getDeptNo());
        if (count > 0) {
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }

        User user = BeanUtil.toBean(userDto, User.class);
        user.setUsername(userDto.getEmail());
        userMapper.updateByPrimaryKeySelective(user);

        if (CollUtil.isEmpty(userDto.getRoleVoIds())) {
            return;
        }

        userRoleMapper.deleteUserRoleByUserId(user.getId());

        List<UserRole> userRoles = new ArrayList<>();
        userDto.getRoleVoIds().forEach(r -> {
            userRoles.add(UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(r))
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build());
        });

        userRoleMapper.batchInsert(userRoles);
    }

    @Override
    public void isenable(Long id, String status) {
        User user = userMapper.selectByPrimaryKey(id);
        user.setDataState(status);
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<UserVo> list(UserDto dto) {
        List<UserVo> vos = userMapper.selectByDtoList(dto);
        return vos;
    }

    @Override
    public void password(Long userId) {
        String password = BCrypt.hashpw(securityProperties.getDefaultPassword(), BCrypt.gensalt());
        User user = User.builder()
                .password(password)
                .id(userId)
                .build();
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public UserVo user() {
        Long id = ThreadLocalUtil.get();
        log.info("====================================={}",id);
        User user = userMapper.selectByPrimaryKey(id);
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);

        List<Role> roleList = roleMapper.findRoleListByUserId(userVo.getId());
        Set<String> roleNames = roleList.stream().map(role -> role.getRoleName()).collect(Collectors.toSet());
        userVo.setRoleNames(roleNames);

        Dept dept = deptMapper.selectByDeptNo(user.getDeptNo());
        userVo.setDeptName(dept.getDeptName());

        Post post = postMapper.selectByPostNo(user.getPostNo());
        userVo.setPostName(post.getPostName());

        return userVo;
    }

  /*  @Override
    public List<UserVo> list(UserDto dto) {
        userMapper.selectList(dto)

        return null;
    }*/
}
